// 云函数入口文件
const cloud = require('wx-server-sdk')
const request = require('request')
cloud.init()
const db = cloud.database();
// ---------------------------------------------
// 函数说明：使用积分支付
// 返回格式: {result:success/fail, error:'错误说明',more:''}

exports.main = async (event, context) => {

  let openid = event.openid
  let userid = event.userid
  let totalFee = event.totalFee
  let outTradeNo = event.outTradeNo
  let template_cardid = event.template_cardid

  // ********************【查询数据库】********************
  let list = await db.collection('users').where({ openid: openid }).get()
  //------------- 错误检测-err01：数据库访问是否正常
  if (list.errMsg != 'collection.get:ok') {
    return { result: 'fail', error: 'err01:网络错误', more: '读取user数据库错误' }
  }
  let userlist = list.data //记录查询结果 [array]
  //------------- 错误检测-err02：会员信息是否唯一
  if (userlist.length != 1) {
    return { result: 'fail', error: 'err02:用户状态不安全，请联系店家', more: userlist }
  }
  //------------- 错误检测-err03：用户是否已经绑定会员卡
  let user = userlist[0]
  if (!user.cardid || user.cardid.length !== 12) {
    return { result: 'fail', error: 'err03:用户尚未绑定会员卡', more: '用户尚未绑定会员卡' }
  }
  let cardid = user.cardid //用户的会员卡号
  // ********************【获取公众号token】********************
  let tokenPromise = await cloud.callFunction({ name: 'getPublicAccessToken' })
  //------------- 错误检测-err04：获取公众号token的云函数是否正确执行
  if (tokenPromise.errMsg != 'callFunction:ok') {
    return { result: 'fail', error: 'err04:网络错误', more: '云函数getPublicAccessToken运行错误' }
  }
  //------------- 错误检测-err05：获取公众号token的云函数是否正确执行
  let token = tokenPromise.result
  if (token == '') {
    return { result: 'fail', error: 'err05:网络错误', more: '云函数getPublicAccessToken返回为空' }
  }
  // ********************【调用腾讯API接口：获取用户会员卡信息】********************
  let url = "https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=" + token;
  let postData = { card_id: template_cardid, code: cardid }
  let userCardInfoRequest = await postRequest(url, postData)
  //------------- 错误检测-err06: 调用腾讯API接口验证数据信息
  if (userCardInfoRequest === false) {
    return { result: 'fail', error: 'err06:网络错误', more: '会员卡新信息查询API调用失败' }
  }
  let cardInfo = userCardInfoRequest
  //------------- 错误检测-err07: 卡片信息是否有误
  if (cardInfo.errcode !== 0) {
    return { result: 'fail', error: 'err07:卡片信息错误', more: cardInfo }
  }
  //------------- 错误检测-err08: 用户是否激活卡片
  if (cardInfo.has_active !== true) {
    return { result: 'fail', error: 'err08:会员卡未激活', more: cardInfo }
  }
  //------------- 错误检测-err09: 用户卡片状态是否正常
  if (cardInfo.user_card_status !== "NORMAL") {
    return { result: 'fail', error: 'err09:会员卡状态异常', more: cardInfo }
  }
  //------------- 错误检测-err10: 用户积分是否支持支付
  let bonus = parseInt(cardInfo.bonus) //用户会员卡当前积分
  if (bonus < totalFee) {
    return { result: 'fail', error: 'err10:积分余额不足', more: cardInfo }
  }
  // ********************【调用腾讯API接口：进行积分扣除】********************
  let url2 = "https://api.weixin.qq.com/card/membercard/updateuser?access_token=" + token;
  let record_bonus = totalFee > 0 ? '消费' + totalFee + '元,使用' + totalFee + '积分' : '充值' + (-totalFee) + '积分'
  let postData2 = { code: cardid, card_id: template_cardid, add_bonus: -totalFee, record_bonus: record_bonus }
  let accountsSub = await postRequest(url2, postData2)
  //------------- 错误检测-err11: 调用腾讯API接口验证数据信息
  if (accountsSub === false) {
    return { result: 'fail', error: 'err11:网络错误', more: '更改用户会员卡信息API调用失败' }
  }
  //------------- 错误检测-err12: 更改用户会员卡信息API调用失败
  if (accountsSub.errcode !== 0) {
    return { result: 'fail', error: 'err12:更改用户会员卡信息API调用失败', more: accountsSub }
  }
  // ********************【将积分消费订单记录至数据库】********************
  let detail = totalFee > 0 ? '消费' + totalFee + '元,使用' + totalFee + '积分' : '充值' + (-totalFee) + '积分'
  let recordOrder = await db.collection('pointsPayRecord').add({
    // data 字段表示需新增的 JSON 数据
    data: {
      userid:userid,
      openid: openid,
      orderid:outTradeNo,
      date: new Date(),
      cost: totalFee,
      detail: detail
    }
  })
  //------------- 错误检测-err13: 积分消费记录云函数执行失败
  if (recordOrder.errMsg !== "collection.add:ok") {
    return { result: 'fail', error: 'err13:积分消费记录云函数执行失败', more: recordOrder }
  }
  // ********************【运行至此说明所有操作无误】********************
  return { result: 'success', error: '', more: '' }
}

async function postRequest(url, postData) {
  //新建promise对象，发起http统一下单请求
  return new Promise((resolve, reject) => {
    try {
      request.post({
        url: url,
        method: "POST",
        json: true,
        headers: {
          "content-type": "application/json",
        },
        body: postData
      },
        function (error, response, body) {
          if (!error && response.statusCode == 200) {
            return resolve(body)
          } else {
            //return reject(error)
            return false
          }
        })
    } catch (e) {
      //return reject(e)
      return false
    }
  })
}